import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'


const request = axios.create({
  baseURL: '/api',
  timeout: 6000
})

request.interceptors.request.use(
  (config) => {
    let loginUser = JSON.parse(localStorage.getItem('loginUser'))
    if(loginUser)
    {
      config.headers.token = loginUser.token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)


request.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if(error.response.status === 401)
    {
      ElMessage.error('登录失败，请重新登录！')
      router.push('/login')
    }else {
      ElMessage.error('接口访问失败！')
    }
    return Promise.reject(error)
  }
)

export default request